//
//  JDCityUnionViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/2/6.
//

import UIKit
import JXSegmentedView
import SwiftyJSON

class JDCityUnionViewController: JDBaseViewController {

    var dragonUserNumber: Int = 0
    var segmentedTitleDataSource = JXSegmentedTitleDataSource()
    var segmentedView = JXSegmentedView()
    lazy var listContainerView: JXSegmentedListContainerView = {
        return JXSegmentedListContainerView(dataSource: self)
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupConfig()
        self.setupUIElements()
//        self.getDragonUnionUserNums()
        self.perform(#selector(getDragonUnionUserNums), with: nil, afterDelay: 1)
        
        // Do any additional setup after loading the view.
    }
    
    func setupConfig() {
        self.setupNavigationTitle("尨商圈")
        self.removeSeparatorLine()
        self.customImageLeftBarButtonItem("xlbLogo", #selector(leftButtonAction), self)
//        self.clearRightBarButtonItem()
//        self.customRightImageButton(#selector(releaseMessageAction))
        // 可以的
//        DispatchQueue.main.asyncAfter(deadline: .now()+5) {
//            self.clearRightBarButtonItem()
//        }
        self.customRightImageButton("发圈", #selector(releaseMessageAction))
    }

    @objc func leftButtonAction() {
        print("左上角的按钮")
//        if #available(iOS 16.0, *) {
//            self.navigationItem.rightBarButtonItem?.isHidden = true
//        } else {
//            // Fallback on earlier versions
//        }
    }
    
    @objc func releaseMessageAction() {
        printLog("我要发布圈内商讯")
        let releaseUnionNewsVC = JDReleaseUnionNewsViewController()
        self.hidesBottomBarPushViewController(releaseUnionNewsVC)
    }
    
    func setupUIElements() {
//        make.top.equalTo(self.view).offset(UIDevice().safeAreaInset.top+14)
        //1、初始化JXSegmentedView
        segmentedView.frame = CGRect(x: 12, y: 14+statusBarHeight+44, width: screenWidth-24, height: 52)
        segmentedView.layer.cornerRadius = 26
        segmentedView.backgroundColor = UIColor.white
//        segmentedView.layer.cornerRadius = 26;
        segmentedView.clipsToBounds = true
        segmentedView.delegate = self
        segmentedView.dataSource = segmentedTitleDataSource
//        segmentedView.contentScrollView = self.contentScrollView
        
        //2、配置数据源
        //segmentedViewDataSource一定要通过属性强持有！！！！！！！！！
        
        segmentedTitleDataSource.titles = ["圈内商讯","尨商圈"]//["尨商圈", "圈内商讯"]//, "同城分享"]
        segmentedTitleDataSource.isTitleColorGradientEnabled = true
        segmentedTitleDataSource.titleSelectedFont = UIFont.systemFont(ofSize: 16, weight: .semibold)
        segmentedTitleDataSource.titleNormalFont = UIFont.systemFont(ofSize: 16, weight: .regular)
        segmentedTitleDataSource.titleNormalColor = UIColor.init(hexString: "#333333")
        segmentedTitleDataSource.titleSelectedColor = UIColor.init(hexString: "#333333")
        
        //3、配置指示器
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = JXSegmentedViewAutomaticDimension
        indicator.lineStyle = .lengthen
        segmentedView.indicators = [indicator]

        //4、配置JXSegmentedView的属性
        self.view.addSubview(segmentedView)

        //5、初始化JXSegmentedListContainerView
        // TODO: 这个地方还需要适配
//        listContainerView.frame = CGRectMake(0, 14+52+statusBarHeight+44, screenWidth, screenHeight-(14+52)-UIDevice().safeAreaInset.bottom-UIDevice().safeAreaInset.top-44-statusBarHeight)
        listContainerView.frame = CGRectMake(0, 14+52+statusBarHeight+44, screenWidth, screenHeight-(14+statusBarHeight+44+52)-UIDevice().safeAreaInset.bottom)
        
        
        self.view.addSubview(listContainerView)

        //6、将listContainerView.scrollView和segmentedView.contentScrollView进行关联
        self.segmentedView.listContainer = listContainerView
        
        self.segmentedView.reloadData()
    }
    
    @objc func getDragonUnionUserNums() {
        JDNetWorkRequest(.getDragonUnionUserNums([:])) { responseStr in
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                // 成功
                self.dragonUserNumber = (JSON(commonModel?.data as Any).dictionary?["count"])?.intValue ?? 0
                
                NotificationCenter.default.post(name: NSNotification.Name("refreshDragonUserNum"), object: nil,userInfo: ["dragonUserNum": self.dragonUserNumber])
//                NotificationCenter.default.post(name: NSNotification.Name("refreshTotalNum"), object: nil,userInfo: ["totalNum": self.totalNum])
                
                
             // TODO: 发送通知
            }
//        查询成功:{"msg":"ok","data":{"count":2},"code":0}
        } failure: { error in
            
        } error: { errorCode in
            
        }

    }
    
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension JDCityUnionViewController: JXSegmentedViewDelegate {
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {

    }
    func segmentedView(_ segmentedView: JXSegmentedView, didScrollSelectedItemAt index: Int) {

    }
}

extension JDCityUnionViewController: JXSegmentedListContainerViewDataSource {
    
    func segmentedView(_ segmentedView: JXSegmentedView, didClickSelectedItemAt index: Int) {
        if index == 0 {
            self.customRightImageButton("发圈",#selector(releaseMessageAction))
        } else if index == 1 {
            self.clearRightBarButtonItem()
        }
    }
    
    
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        return segmentedTitleDataSource.dataSource.count
    }

    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {

        if index == 0 {
            // 圈内商讯
            let cityUnionMessageVC = JDCityUnionMessageViewController()
            cityUnionMessageVC.dragonUserNumber = self.dragonUserNumber
            cityUnionMessageVC.baseVC = self
            print("圈内商讯")
            return cityUnionMessageVC
        }else if index == 1 {
            // 龙商圈
            let cityUnionListVC = JDCityUnionListViewController()
            cityUnionListVC.dragonUserNumber = self.dragonUserNumber
            
            print("龙商圈")
            return cityUnionListVC
        }else {
            // 同城分享
            let cityShareVC = JDCityShareViewController()
            return cityShareVC
//            // TODO: 同城分享 还需要修改
//            let comprehensiveVC = JDComprehensiveViewController()
//            print("这是3")
//            return comprehensiveVC
        }
    }
}
